<template>
	<view>
		<view class="cart-list">
			
			<view class="cart-item" v-for="item in cartList">
				 <evan-checkbox v-model="item.checked">
					 {{item.productName}} -- {{item.price}} -- {{item.quantity}}
				 </evan-checkbox>
				
			</view>
		</view>
		
		<view >
			<evan-checkbox v-model="isAllChecked">全选</evan-checkbox>
			<view>总价：{{totalPrice}}</view>
			<button type="primary" @tap="settlement">结算</button>
		</view>
	</view>
</template>

<script>
	import {
		findAllCartItem
	} from '@/api/user/cart/index.js'
	import {
		addPreOrder
	} from '@/api/productDetail/index.js'
	export default {
		name:"Cart",
		data() {
			return {
				// checked:false,
				cartList:[]
			};
		},
		onLoad(){
			
		},
		computed:{
			isAllChecked:{
				get(){
					return this.cartList.every(item=>item.checked)
				},
				set(val){
					this.cartList.forEach(item=>item.checked=val)
				}
				
			},
			totalPrice(){
				return this.cartList.reduce((total,current)=>{
					if(current.checked){
						return total + current.price * current.quantity
					}else{
						return total
					}
				},0)
			}
		},
		onShow(){
			this.getCartList()
		},
		methods:{
			async getCartList(){
				const res = await findAllCartItem()
				res.data.items.forEach(item=>{
					item.checked = false
				})
				this.cartList = res.data.items
			},
			 async settlement(){
				// 1. 过滤哪个商品被选中
				const checkedProductList = this.cartList.filter(item=>item.checked)
				let orderItemList = []
				checkedProductList.forEach(item=>{
					orderItemList.push({
						  "cartId": item.id,
						  "productId": item.productId,
						  "productQuantity": item.quantity,
						  "productSkuId": item.productSkuId
						})
				})
				
				const res = await addPreOrder({"orderItemList":orderItemList})
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>
